import os
import subprocess
import time
import threading
import multiprocessing

from base import config
from util.base_util import MyError, BaseUtil as util, mark
from util.user_log import log

uid = config.devices
port01 = config.appium_port01
port02 = config.appium_port02
dir_log = config.FileDir.appium_log
address = config.appium_address


class DosCmd:
    @staticmethod
    def execute_cmd_res(command, timeout=2):
        # 支持中文
        log.debug('执行cmd：{}'.format(command))
        p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
        try:
            p.wait(timeout)
        except subprocess.TimeoutExpired:
            p.kill()
            raise MyError('超时！请检查命令参数是否正确: \n{}'.format(command))
        read_lines = str(p.stdout.read(), encoding='utf-8').split('\r\n')
        read_lines = [i for i in read_lines if i]
        return read_lines

    @staticmethod
    def execute_cmd(command):
        log.debug('执行cmd：{}'.format(command))
        os.system(command)

    @staticmethod
    def execute_os_popen(command):
        # 无法解码带有中文的返回值
        log.debug('执行cmd：{}'.format(command))
        res = os.popen(command).readlines()
        res = list(map(lambda x: x.replace('\n', ''), res))
        res = [i for i in res if i]
        return res


class Server(DosCmd):
    check_5037 = 'netstat -ano | findstr 5037'
    devices = 'adb devices'
    process_adb, process_appium = 'adb.exe', 'node.exe'
    check_process = 'tasklist /nh|find /i '

    connect_cmd = 'adb connect ' + uid  # 无线连接

    def __init__(self):
        self.is_adb_exist = self.ensure_process(self.process_adb)
        self.is_appium_exist = self.ensure_process(self.process_appium)

    def ensure_process(self, name):
        # 检测adb、appium是否已经启动
        cmd = self.check_process + '"{}"'.format(name)
        res = self.execute_cmd_res(cmd)
        if len(res) > 1 and name in res[1]:
            log.debug('进程已启动：{}'.format(name))
            return True
        else:
            log.debug('进程未启动：{}'.format(res))

    def start_adb(self):
        # 启动adb
        if self.is_adb_exist:
            self.is_adb_exist = True
            return log.debug('adb已启动')
        res = self.execute_cmd_res(self.check_5037)
        if len(res) > 1:
            raise MyError('adb端口被占用！{}'.format(res))
        else:
            log.debug('启动adb')
            self.execute_os_popen(self.devices)
            self.is_adb_exist = True

    def connect_devices(self, cmd=None):
        # 检测是否已连接设备
        res = self.execute_cmd_res(self.devices)
        key_word = '\tdevice'
        list01 = [i.strip().replace(key_word, '') for i in res if key_word in i]

        if not list01:
            # 设备未连接，执行连接
            res = self.execute_cmd_res(self.connect_cmd)
            log.debug('连接成功') if 'connected' in res[1] else None
            return res
        log.debug('设备已连接')

    def start_appium(self):
        if not self.is_appium_exist:
            thread = threading.Thread
            # process = multiprocessing.Process
            obj__ = thread(target=self.execute_appium, daemon=True)
            obj__.setDaemon(True)
            obj__.start()
            obj__.join(timeout=3)
            if self.ensure_process(self.process_appium):
                self.is_appium_exist = True
                log.debug('appium服务启动成功')
            return None

    @staticmethod
    def execute_appium(log_level='warn'):
        # log_level = debug < info< warn< error
        params = (port01, port02, uid, dir_log, address, log_level)
        cmd = 'appium -p {} -bp {} -U {} --log {} -a {} ' \
              '--session-override --local-timezone --log-level {}'.format(*params)
        log.debug('appium启动命令：{}'.format(cmd))
        os.system(cmd)

    def close_server(self, name=process_adb):
        # print(self.is_adb_exist)
        def func(name):
            cmd = 'taskkill /F /IM {} /t'.format(name)
            res = self.execute_cmd_res(cmd)
            if len(res) > 1 and 'SUCCESS' in res[1]:
                log.debug('服务关闭成功：{}'.format(name))
            elif len(res) > 1 and 'not found' in res[1] == 1:
                log.debug('服务不存在：{}'.format(name))
            return res

        if 'adb' in name and self.is_adb_exist:
            return func(name)
        elif 'node' in name and self.is_appium_exist:
            return func(name)
        else:
            log.debug('服务不存在，不需要关闭; {}, {}'.format(name, self.is_adb_exist))

    def __call__(self, *args, **kwargs):
        self.start_adb()
        self.connect_devices()
        self.start_appium()


if __name__ == '__main__':
    server = Server()
    server.start_adb()
    server.connect_devices()
    # server.__call__()
    # server.close_server(server.process_appium)
    # server.start_appium()
    # server.start_adb()
    # server.start_appium()
